package cn.yi.medicalsys.controller;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import cn.yi.medicalsys.pojo.News;
import cn.yi.medicalsys.service.CaseService;
import cn.yi.medicalsys.service.NewsService;
import cn.yi.medicalsys.service.impl.CaseServiceImpl;
import cn.yi.medicalsys.service.impl.NewsServiceImpl;
import cn.yi.medicalsys.utils.StringUtils;


public class NewsServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}
	
	public void doPublisNews(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		PrintWriter out = response.getWriter();
		boolean isOK = false; // 图片上传是否成功
		boolean isOnlyText = false; // 是否为文字新闻
		String uploadPath = request.getServletContext().getRealPath("/")
				+ File.separator + "upload";
		// 如果目录不存在则创建
		File uploadDir = new File(uploadPath);
		if (!uploadDir.exists()) {
			uploadDir.mkdir();
		}
		News news = new News();
		// 1:判断表单提交的内容形式
		boolean isMultipart = ServletFileUpload.isMultipartContent(request);
		if (isMultipart) {
			// 2:创建文件上传所需的API实例
			FileItemFactory factory = new DiskFileItemFactory();
			ServletFileUpload upload = new ServletFileUpload(factory);
			// 3:解析request请求，获取FileItem对象集合
			List<FileItem> list = upload.parseRequest(request);
			// 4:循环遍历集合中的数据
			for (FileItem item : list) {
				if (item.isFormField()) {
					// 对象为普通表单
					String fieldName = item.getFieldName();
					if ("ntitle".equals(fieldName)) {
						news.setNtitle(item.getString("UTF-8"));
					} else if ("nsummary".equals(fieldName)) {
						news.setNsummary(item.getString("UTF-8"));
					} else if ("nauthor".equals(fieldName)) {
						news.setNauthor(item.getString("UTF-8"));
					} else if ("ncontent".equals(fieldName)) {
						news.setNcontent(item.getString("UTF-8"));
					}
				} else {
					// 对象为文件表单
					String name = item.getName();
					if (name != null && !"".equals(name)) {
						// 控制文件的上传的类型
						if (!StringUtils.checkImg(name)) {
							out.println("<script>alert('新闻图片的格式不正确，请重新选择');history.back();</script>");
						} else {
							String fileName = StringUtils.getNewName(name);
							news.setnImage(fileName);
							// 远程服务器的文件地址
							File file = new File(uploadPath, fileName);
							item.write(file);
							isOK = true;
						}
					} else {
						isOnlyText = true;
					}

				}

			}
		}
		if (isOnlyText || isOK)

		{
			// 调用业务逻辑层
			NewsService newsService = new NewsServiceImpl();
			news.setNcreateDate(new Date());
			boolean result = newsService.addNews(news);
			if (result) {
				// 发布成功
				out.println("<script>alert('恭喜您，新闻发布成功');location.href='addnew.jsp';</script>");
				// 发布失败
			} else {
				out.println("<script>alert('发布失败');history.back();</script>");
			}
		}
	}
	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		this.doPost(request, response);
	}

	/**
	 * The doPost method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to post.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		// 相应的格式
				response.setContentType("text/html;charset=UTF-8");
				// 是用post的方式提交的
				// 接受请求的格式
				request.setCharacterEncoding("UTF-8");
				// 接收处理的参数
				String action = request.getParameter("action");

				if (action != null && !"".equals(action)) {
					if ("newsadd".equals(action)) {
						//发布新闻
						try {
							this.doPublisNews(request, response);
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
				} else {
					response.sendRedirect("index.jsp");
				}

			}

	/**
	 * Initialization of the servlet. <br>
	 *
	 * @throws ServletException if an error occurs
	 */
	public void init() throws ServletException {
		// Put your code here
	}

}
